import http from '@/utils/http'
import { isLoggedIn } from '@/utils/auth'

export const lessonDetailMixin = {
  data() {
    return {
      loggedIn: false,
      lesson: null,
      sentences: [],
      vocabulary: [],
      userVocabulary: [],
      loading: true,
      error: null,
      showNotification: false,
      notificationMessage: '',
      notificationDialogTitle: 'Coming Soon',
      lessonProgress: null,
    }
  },
  async mounted() {
    const lessonId = this.$route.params.id
    const coursePath = this.$route.params.coursePath
    await this.loadLessonDetails(lessonId, coursePath)
    // 加载课程进度
    await this.loadLessonProgress(lessonId)
    this.loggedIn = isLoggedIn()
  },
  methods: {
    getLessonProgress() {
      if (this.lessonProgress > 0 && this.lessonProgress < 1) return 1.0;
      if (this.lessonProgress > 99.0 && this.lessonProgress < 100.0) return 99.0;
      return Math.round(this.lessonProgress);
    },
    async loadLessonDetails(lessonId, coursePath) {
      try {
        let response;
        if (coursePath) {
          // Use the new route with course path
          response = await http.get(`/lessons/${coursePath}/${lessonId}`)
        } else {
          // Fallback to the old route (may need to find course path)
          response = await http.get(`/lessons/${lessonId}`)
        }
        this.lesson = response

        this.loading = false
      } catch (err) {
        this.error = 'Failed to load lesson details'
        this.loading = false
        console.error(err)
      }
    },

    // 添加加载课程进度的方法
    async loadLessonProgress(lessonId) {
      try {
        if (!isLoggedIn()) return;
        const response = await http.get(`/progress/lessons?lesson_id=${lessonId}&course_path=${this.$route.params.coursePath}`)
        if (response && response.length > 0) {
          this.lessonProgress = Number.parseFloat(response[0].completion_percentage) || 0
          this.lessonProgress > 100 && (this.lessonProgress = 100)
        } else {
          this.lessonProgress = 0
        }
      } catch (err) {
        console.error('Failed to load lesson progress:', err)
        this.lessonProgress = 0
      }
    },

    hideNotification() {
      this.showNotification = false
    }
  }
}